package com.moxigua.iotbox.func.sensor;


import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.moxigua.iotbox.R;
import com.moxigua.iotbox.base.BaseApplication;
import com.moxigua.iotbox.base.BaseFragment;
import com.moxigua.iotbox.base.Constants;
import com.moxigua.iotbox.bean.MqttAction;
import com.moxigua.iotbox.bean.RequestMessage;
import com.moxigua.iotbox.bean.ResponseCollection;
import com.moxigua.iotbox.func.MqttClientHepler;
import com.moxigua.iotbox.func.event.BaseEvent;
import com.moxigua.iotbox.util.SPUtils;
import com.moxigua.iotbox.util.TimeUtil;
import com.orhanobut.logger.Logger;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.moxigua.iotbox.util.TimeUtil.FORMAT_DATE_TIME;

/**
 * A simple {@link Fragment} subclass.
 * 传感器显示页面
 */
public class SensorFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.tv_time)
    TextView mTvTime;
    @BindView(R.id.tv_air_temp)
    TextView mTvAirTemp;
    @BindView(R.id.tv_air_hum)
    TextView mTvAirHum;
    @BindView(R.id.tv_soild_temp)
    TextView mTvSoildTemp;
    @BindView(R.id.tv_soild_hum)
    TextView mTvSoildHum;
    @BindView(R.id.tv_light)
    TextView mTvLight;
    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout mSwipeLayout;
    private MqttClient mMqttClient;
    private Gson mGson;


    public SensorFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
//        // Inflate the layout for this fragment
        mGson = new Gson();
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }
        View view = inflater.inflate(R.layout.fragment_sensor, container, false);
        ButterKnife.bind(this, view);
        mSwipeLayout.setOnRefreshListener(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onRefresh();
            }
        }, 1500);
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseEvent(BaseEvent event) {
        List<MqttAction<ResponseCollection, Double>> mqttActions = new ArrayList<MqttAction<ResponseCollection, Double>>();
        Type type = new TypeToken<ArrayList<MqttAction<ResponseCollection, Double>>>() {}.getType();
        if (event.topic.equals(Constants.TOPIC_SUB_REMOTE)) {
            //收到的数据格式为数组
            String json = event.message.toString();
            if (json.contains("\"AirTemp\"")) {
                mSwipeLayout.setRefreshing(false);
                //包含此单词说明是采集点的数据
                mqttActions = mGson.fromJson(json, type);
                if (mqttActions.size() > 0) {
                    //验证是否是本设备所需数据
                    MqttAction<ResponseCollection, Double> action = mqttActions.get(0);
                    if (action.getTags().getClientID() == (Integer) SPUtils.get(Constants.SP_CLIENT_ID, 0) && action.getTags().getCollectionID() == Constants.DEFAULT_COLLECTION_ID) {
                        mTvTime.setText(TimeUtil.longToString(new Date().getTime(), FORMAT_DATE_TIME));
                        for (MqttAction<ResponseCollection, Double> act : mqttActions) {
                            String value = String.valueOf(act.getValue());
                            switch (act.getMetric()) {
                                case Constants.METRIC_RESPONSE_AIRTEMP:
                                    mTvAirTemp.setText(value.length() > 5 ? value.substring(0, 5) : value);
                                    break;
                                case Constants.METRIC_RESPONSE_AIRHUM:
                                    mTvAirHum.setText(value.length() > 5 ? value.substring(0, 5) : value);
                                    break;
                                case Constants.METRIC_RESPONSE_SOLIDTEMP:
                                    mTvSoildTemp.setText(value.length() > 5 ? value.substring(0, 5) : value);
                                    break;
                                case Constants.METRIC_RESPONSE_SOLIDHUM:
                                    mTvSoildHum.setText(value.length() > 5 ? value.substring(0, 5) : value);
                                    break;
                                case Constants.METRIC_RESPONSE_LIGHT:
                                    mTvLight.setText(String.valueOf(act.getValue()));
                                    break;
                            }
                        }
                    }
                }
            }
        } else {
//            Logger.e(event.toString());
        }
    }

    @Override
    public void onRefresh() {
        if (BaseApplication.isOnline() && MqttClientHepler.getInstance().isConnect()) {
            //传递MQTT指令，等待采集点返回数据
            MqttAction<RequestMessage, Double> messageMqttAction = new MqttAction<>();
            messageMqttAction.setMetric(Constants.METRIC_REQUEST_MESSAGES);
            messageMqttAction.setValue(Double.valueOf(0));
            RequestMessage requestMessage = new RequestMessage();
            int randomPacketId = (int) (Math.random() * 10000);
            BaseApplication.setLastPacketId(randomPacketId);
            requestMessage.setPacketID(randomPacketId);
            requestMessage.setClientid((Integer) SPUtils.get(Constants.SP_CLIENT_ID, 0));
            requestMessage.setCollectionID(Constants.DEFAULT_COLLECTION_ID);
            messageMqttAction.setTags(requestMessage);
            String payload = "[" + new Gson().toJson(messageMqttAction) + "]";

            MqttClientHepler.getInstance().publish(Constants.TOPIC_PUB_COL, 1, payload.getBytes());
        } else {
            showShortToast("尚未连接\n稍后再试");
            mSwipeLayout.setRefreshing(false);
        }
    }
}
